//
//  MKUITableViewCellSwipeAction.m
//  MKUI
//
//  Created by 苏尚进 on 2020/8/24.
//  Copyright © 2020 moon. All rights reserved.
//

#import "MKUITableViewCellSwipeAction.h"
#import "MKUIPreCompile.h"
#import "MKUITableViewCellModel.h"
@interface MKUITableViewCellSwipeAction ()
@property (nonatomic, assign) MKUITableViewCellSwipeActionStyle style;
@property (nonatomic, copy) MKUITableViewCellSwipeActionHandler handler;
@end

@implementation MKUITableViewCellSwipeAction
- (id)init{
    if (self=[super init]) {
        self.autoCompletion = YES;
    }
    return self;
}
+ (instancetype)actionWithStyle:(MKUITableViewCellSwipeActionStyle)style title:(nullable NSString *)title handler:(MKUITableViewCellSwipeActionHandler)handler{
    MKUITableViewCellSwipeAction *action = [[MKUITableViewCellSwipeAction alloc] init];
    action.title = title;
    action.handler = handler;
    action.style = style;
    return action;
}
- (UIContextualAction *)contextualActionWithCellModel:(MKUITableViewCellModel *)cellModel{
    @MK_WEAKIFY(self);
    @MK_WEAKIFY(cellModel);
    UIContextualAction *rowAction = [UIContextualAction contextualActionWithStyle:self.style==MKUITableViewCellSwipeActionStyleDestructive?UIContextualActionStyleDestructive:UIContextualActionStyleNormal title:self.title handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        @MK_NORMALIZE(self);
        @MK_NORMALIZE(cellModel);
        if(self.handler){
            self.handler(self, cellModel);
            if(self.autoCompletion){
                completionHandler(YES);
            }
        }
    }];
    rowAction.image = self.image;
    rowAction.backgroundColor = self.backgroundColor;
    return rowAction;
}
- (UITableViewRowAction *)tableViewRowActionWithCellModel:(MKUITableViewCellModel *)cellModel{
    @MK_WEAKIFY(self);
    @MK_WEAKIFY(cellModel);
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:self.style==MKUITableViewCellSwipeActionStyleDestructive?UITableViewRowActionStyleDestructive:UITableViewRowActionStyleNormal title:self.title handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        @MK_NORMALIZE(self);
        @MK_NORMALIZE(cellModel);
        if(self.handler){
            self.handler(self, cellModel);
            if(self.autoCompletion){
                [cellModel refreshWithAnimated:YES];
            }
        }
    }];
    if(self.backgroundColor){
        rowAction.backgroundColor = self.backgroundColor;
    }
    return rowAction;
}
- (void)dealloc{
    
}
@end
